package se.jocke.nb.log.internal;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import se.jocke.nb.log.LineListener;
import se.jocke.nb.log.LogReader;
import se.jocke.nb.log.TailListener;

/**
 *
 * @author jocke
 */
public class LogReaderImpl implements LogReader {

    private final File file;

    private Tailer tailer;
    
    private Seeker seeker;

    public LogReaderImpl(File file) {
        this.file = file;
    }

    @Override
    public void tail(TailListener listener) {

        if (tailer != null) {
            tailer.setRunning(false);
        }

        try {
            this.tailer = new Tailer(file, 20, listener);
            Thread t = new Thread(tailer);
            tailer.setRunning(true);
            t.start();
        } catch (IOException ex) {
            listener.onIOException(ex);
        }
    }

    @Override
    public void close() {
        if (tailer != null) {
            try {
                tailer.close();
            } catch (IOException ex) {
                Logger.getLogger(LogReaderImpl.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    @Override
    public void seek(boolean fromTop, int maxResult, LineListener listener) {
       
        if (seeker != null) {
            seeker.setRunning(false);
        }

        try {
            this.seeker = new Seeker(file, listener, maxResult, fromTop);
            Thread t = new Thread(seeker);
            seeker.setRunning(true);
            t.start();
        } catch (IOException ex) {
            listener.onIOException(ex);
        }
           
        
    }

}
